﻿using blackhouse.BlackApart.Business.Apartments;
using blackhouse.BlackApart.Business.Furnitures;
using blackhouse.BlackApart.Business.Reservations;
using blackhouse.BlackApart.Web;
using blackhouse.BlackApart.WebNemo;
using blackhouse.JavaScript.JQuery;
using mojoPortal.Web;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using blackhouse;
using blackhouse.WebNemo.Web;
using blackhouse.BlackApart.Web.Navigation;
using blackhouse.StareKino.Web.Modules;
using blackhouse.mojoPortalExtend;
using System.IO;
using blackhouse.WebNemo.Business.Groups;
using blackhouse.Translator.Web;

namespace blackhouse.StareKino.Web {
    public partial class Apartment : NonCmsBasePage {

        #region Fields

        private Size referencePhotoSize = new Size(1000, 1000);
        private Size furnitureIconSize = new Size(30, 30);

        private int apartmentTypeId = -1;
        private IApartmentGroup group;
        private NemoApartmentType nemoGroup;
        private BlackApart.Business.Factory factory = BlackApart.Business.Factory.Instance();
        private double starsPercentValue = 0;
        private ApartmentGallery photos;
        private SearchState queryState = SearchState.GetFromContext();
        private Variant variant;
        private IFurniture[] furnitures;
        private CinemaActors actors;

        #endregion

        #region Page Cycle

        protected override void OnInit(EventArgs e) {
            base.OnInit(e);
            this.ReadParameters();
        }

        protected override void OnLoad(EventArgs e) {
            base.OnLoad(e);
            if (this.SetScenario()) {
                this.AddJavaScripts();
                this.PopulateView();
                this.SetSeo();
            } else {
                this.Response.Status = "404 Not Found";
                this.Response.StatusCode = 404;
                this.Response.End();
            }
        }

        #endregion

        #region Methods

        private void SetSeo() {
            PageProvider pageProvider = new PageProvider();
            PageSeo seoSetting = this.nemoGroup.GetPageSeo();
            pageProvider.SetSeo(seoSetting);
        }

        private void ReadParameters() {
            string id = Request.QueryString["id"];
            if (!String.IsNullOrEmpty(id))
                Int32.TryParse(id, out this.apartmentTypeId);
        }

        private bool SetScenario() {
            if (this.apartmentTypeId > 0) {
                this.group = this.factory.GetApartmentGroup(this.apartmentTypeId);
                if (this.group != null && this.group.Exists()) {
                    this.nemoGroup = this.group as NemoApartmentType;
                    this.starsPercentValue = Math.Ceiling(this.group.Stars * 100 / 5);
                    if (this.starsPercentValue > 100) this.starsPercentValue = 100;
                    if (this.starsPercentValue < 0) this.starsPercentValue = 0;
                    this.photos = new ApartmentGallery(this.group);
                    if (this.queryState.IsSet)
                        this.variant = this.queryState.GetSearchVariants(this.apartmentTypeId).FirstOrDefault();
                    this.furnitures = this.group.GetFurnitures().OrderBy(f => f.Sort).ThenBy(f => f.Name).ToArray();
                    this.AttachSearchControl();
                    this.actors = new CinemaActors(this.group);
                    return true;
                }
            }
            return false;
        }

        private void AttachSearchControl() {
            OnlineReservation reservationControl = OnlineReservation.GetReservationControl();
            if (reservationControl != null) {
                reservationControl.SeachValueChanged += reservationControl_SeachValueChanged;
                reservationControl.ChangeButtonText(GetGlobalResourceObject("Reservation", "check").ToString());
            }
        }

        void reservationControl_SeachValueChanged(object sender, Aparts.Web.SearchChangedEventArgs args) {
            Response.Redirect(PageProvider.AdjustUrlToCurrentSite(this.group.Url) + "?search=" + args.GetState().ToString());
        }

        private void PopulateView() {

            this.pnlApartmentWrapper.CssClass = this.pnlApartmentWrapper.CssClass + " q-" + (this.queryState.IsSet ? "set" : "notset");

            this.ltlApartmentName.Text = this.group.Name;
            this.ltlActors.Text = this.actors.ToString();
            this.ltlCinemaDescriptionActors.Text = this.ltlActors.Text;
            this.pnlStars.Width = Unit.Percentage(this.starsPercentValue);
            if (this.photos.Count == 0)
                this.rptApartmentGallery.Visible = false;
            else {
                this.rptApartmentGallery.DataSource = this.photos;
                this.rptApartmentGallery.DataBind();
            }
            this.detailsTable.PopulateControl(this.group, this.variant);
            this.ltlCinemaDescription.Text = this.nemoGroup.GetString("opis_filmu");
            this.ltlShortCinemaDescription.Text = this.ltlCinemaDescription.Text.SubstringToWord(500);
            this.ltlDescription.Text = this.group.Description;
            if (this.furnitures.Length == 0)
                this.rptFurnitures.Visible = false;
            else {
                this.rptFurnitures.DataSource = this.furnitures.Select(f => new DisplayFurniture(f, this.furnitureIconSize));
                this.rptFurnitures.DataBind();
            }
            if (this.nemoGroup != null && this.nemoGroup.IsNotNull("schemat_apartamentu")) {
                this.lnkToScheme.NavigateUrl = this.nemoGroup.GetImageUrl("schemat_apartamentu", new Size(1000, 1000));
                this.lnkToScheme.Attributes.Add("data-open", "popup");
            } else
                this.lnkToScheme.Visible = false;

            if (this.nemoGroup != null && this.nemoGroup.IsNotNull("spacer")) {
                this.lnkToWalk3D.NavigateUrl = "/Walk3DHand/Preview.aspx?id=" + this.group.Id;
                this.lnkToWalk3D.Attributes.Add("data-open", "popup-flash");
            } else
                this.lnkToWalk3D.Visible = false;

            if (this.variant == null)
                this.bntCheckAvability.Visible = true;
            else {
                this.bntBook.Visible = true;
                this.bntBook.NavigateUrl = NavigationProvider.Instance().GetUrl(ReservationPage.GetPreInformationPage(this.group.Id));
            }
            if (WebNemo.Business.Factory.Instance().GetCurrentUser().HasSufficientPermissions(false)) {
                this.pnlActionLinks.Visible = true;
                using (StringWriter sw = new StringWriter())
                using (HtmlTextWriter writer = new HtmlTextWriter(sw)) {
                    writer.RenderBeginTag(HtmlTextWriterTag.Ul);
                    this.WriteListItem(writer, "Edytuj apartament", this.nemoGroup);
                    GroupRecord shareType = this.nemoGroup.GetRecord("wspoldzielony_typ");
                    if (shareType != null && shareType.Exists)
                        this.WriteListItem(writer, "Edytuj wspólne dane dla: <b>" + shareType.GetString("nazwa") + "</b>", shareType);

                    writer.RenderEndTag();
                    this.ltlActionLinks.Text = sw.ToString();
                }
            }
        }

        private void WriteListItem(HtmlTextWriter writer, string name, GroupRecord record) {
            this.WriteListItem(writer, name, record, String.Empty);
        }

        private void WriteListItem(HtmlTextWriter writer, string name, GroupRecord record, string extraClass) {
            if (!String.IsNullOrEmpty(extraClass))
                writer.AddAttribute(HtmlTextWriterAttribute.Class, extraClass);
            writer.RenderBeginTag(HtmlTextWriterTag.Li);

            writer.AddAttribute(HtmlTextWriterAttribute.Class, "ico");
            writer.RenderBeginTag(HtmlTextWriterTag.Span);
            writer.RenderEndTag();

            NemoUrl nemoUrl = new NemoUrl(NemoUrlView.RecordList);
            nemoUrl.GroupId = record.GetGroup().Id;
            if (record.RecordId > 0) {
                nemoUrl.RecordId = record.RecordId;
                nemoUrl.View = NemoUrlView.EditRecord;
            }
            writer.AddAttribute(HtmlTextWriterAttribute.Href, nemoUrl.GetUrl());
            writer.RenderBeginTag(HtmlTextWriterTag.A);
            writer.Write(name);
            writer.RenderEndTag();

            writer.RenderEndTag();
        }


        private void AddJavaScripts() {
            JQueryLibraries jql = new JQueryLibraries();
            jql.IncludeFileBasedOnJQuery("blackhouse.StareKino.Web.Scripts.apartmentGallery.js,blackhouse.StareKino.Web");
        }

        //private string LocationToString(IApartmentLocation location) {
        //    List<string> addressParts = new List<string>(3);
        //    if (!String.IsNullOrEmpty(location.City))
        //        addressParts.Add(location.City);
        //    if (!String.IsNullOrEmpty(location.District))
        //        addressParts.Add(location.District);
        //    if (!String.IsNullOrEmpty(location.LocationName))
        //        addressParts.Add(location.LocationName);
        //    return String.Join(", ", addressParts.ToArray());
        //}

        protected void ItemDataBound_ApartmentPhotos(object sender, RepeaterItemEventArgs e) {
            switch (e.Item.ItemType) {
                case ListItemType.AlternatingItem:
                case ListItemType.Item:
                    HyperLink lnkPhoto = e.Item.FindControl("lnkPhoto") as HyperLink;
                    IApartmentPhoto photo = e.Item.DataItem as IApartmentPhoto;
                    if (lnkPhoto == null || photo == null) {
                        e.Item.Visible = false;
                        return;
                    }
                    lnkPhoto.NavigateUrl = photo.GetImageUrl(this.referencePhotoSize);
                    lnkPhoto.ToolTip = photo.Description;
                    lnkPhoto.Attributes.Add("data-category", photo.Category);
                    break;
            }
        }

        #endregion

    }
}